<?php

namespace app\forms\position;

use app\forms\Model;
use app\models\User;
use yii\db\Exception;
use yii\web\HttpException;
use app\models\Position;
use app\validators\PositiveInteger;

/**
 * 岗位 详情
 */
class ViewForm extends Model
{
    public $id;

    public function rules()
    {
        return [
            ['id', PositiveInteger::class],
            ['id', 'required', 'message' => 'ID不为空'],
            ['id', 'exist', 'targetClass' => Position::class],
        ];
    }

    /**
     * @param $param
     * @return array
     * @throws HttpException
     */
    public static function view($param)
    {
        $form = new self();
        $form->setAttributes($param);
        !$form->validate() ? $form->validateError() : '';

        try {
            $model = Position::find()->alias('p')->select(['p.id', 'p.name', 'dept_id'])->joinWith([
                'dept' => function ($q) {
                    $q->select(['name']);
                }
            ])->where(['p.id' => $form->id])->one();
            $position = ['name' => $model->name, 'dept' => $model->dept->name];
            $arr = (new User)->getForPosition($form->id);
            $arr['position'] = $position;
            return $arr;

        } catch (Exception $e) {
            $form->serverError();
        }
    }
}